import 'dart:async';

import 'package:flutter/material.dart';

class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  final _globalKey = GlobalKey<AnimatedListState>(); //必须指定类型
  List<String> list = ['1', '2'];
  bool flag = true;

  Widget _buildItem(int index) {
    return ListTile(
      key: ValueKey(index),
      title: Text(list[index]),
      trailing: IconButton(
        icon: Icon(Icons.delete),
        onPressed: () {
          //执行删除
          _deleteImte(index);
        },
      ),
    );
  }

  _deleteImte(index) {
    // print('删除的索引是：$index');
    if (flag) {
      flag = false;
      //执行删除
      _globalKey.currentState!.removeItem(index, (context, animation) {
        var item = _buildItem(index);
        list.removeAt(index);
        // return FadeTransition(opacity: animation, child: item);
        return ScaleTransition(scale: animation, child: item);
      });
      //解决快速删除的bug
      Timer.periodic(Duration(milliseconds: 600), (timer) {
        flag = true;
        timer.cancel();
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            list.add('我是新增的');
            _globalKey.currentState!.insertItem(list.length - 1);
          });
        },
        child: Icon(Icons.add),
      ),
      appBar: AppBar(title: Text('AnimatedList 组件')),
      body: AnimatedList(
        key: _globalKey,
        initialItemCount: list.length,
        itemBuilder: (context, index, animation) {
          // return FadeTransition(opacity: animation, child: _buildItem(index));
          return ScaleTransition(scale: animation, child: _buildItem(index));
        },
      ),
    );
  }
}
